package com.biu.billiards.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

/**
 * @description: 微信登陆工具类
 * @author jianfei.ma
 * @ClassName:GetOpenIdUtil
 * @date:2020/2/18 001816:43
 */
public class GetOpenIdUtil {



    public String getOpenid(String appid, String code, String secret) {
        BufferedReader in = null;
        //appid和secret是开发者分别是小程序ID和小程序密钥，开发者通过微信公众平台-》设置-》开发设置就可以直接获取，
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            URL weChatUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = weChatUrl.openConnection();
            // 设置通用的请求属性
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }


            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }







    public String getOpenDYid(String appid, String code, String secret) {


        String url = "https://developer.toutiao.com/api/apps/v2/jscode2session";
        String param="{\n" +
                "  \"appid\": \""+appid+"\",\n" +
                "  \"secret\": \""+secret+"\",\n" +
                "  \"anonymous_code\": \"\",\n" +
                "  \"code\": \""+code+"\"\n" +
                "}";

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestMethod("POST");
            conn.addRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public String getOpenKSid(String appid, String code, String secret) {


        String param="app_id="+appid+"&js_code="+code+"&app_secret="+secret;

            String result = "";
            try {
                URL url = new URL("https://open.kuaishou.com/oauth2/mp/code2session");
                //通过调用url.openConnection()来获得一个新的URLConnection对象，并且将其结果强制转换为HttpURLConnection.
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                //设置连接的超时值为30000毫秒，超时将抛出SocketTimeoutException异常
                urlConnection.setConnectTimeout(30000);
                //设置读取的超时值为30000毫秒，超时将抛出SocketTimeoutException异常
                urlConnection.setReadTimeout(30000);
                //将url连接用于输出，这样才能使用getOutputStream()。getOutputStream()返回的输出流用于传输数据
                urlConnection.setDoOutput(true);
                //设置通用请求属性为默认浏览器编码类型
                urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                //getOutputStream()返回的输出流，用于写入参数数据。
                OutputStream outputStream = urlConnection.getOutputStream();
                String content =param;
                outputStream.write(param.getBytes());
                outputStream.flush();
                outputStream.close();
                //此时将调用接口方法。getInputStream()返回的输入流可以读取返回的数据。
                InputStream inputStream = urlConnection.getInputStream();
                byte[] data = new byte[1024];
                StringBuilder sb = new StringBuilder();
                //inputStream每次就会将读取1024个byte到data中，当inputSteam中没有数据时，inputStream.read(data)值为-1
                while (inputStream.read(data) != -1) {
                    String s = new String(data, Charset.forName("utf-8"));
                    sb.append(s);
                }
                result = sb.toString();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

}




